#include "OutLineRender.h"

OutLineRender::OutLineRender(const std::string& name):IRender(name)
{
	mVertexNormal = ShaderManager::Instance()->CreateShader(SID_SAMPLE_OUT_LINE_VERTEX_2);
	ShaderManager::Instance()->LoadShader(mVertexNormal);
	CGprogram mVertexProgramNormal = ShaderManager::Instance()->GetProgram(mVertexNormal);
	mParamMvpNormal = cgGetNamedParameter(mVertexProgramNormal, "mvp");

	mVertex = ShaderManager::Instance()->CreateShader(SID_SAMPLE_OUT_LINE_VERTEX);
	ShaderManager::Instance()->LoadShader(mVertex);
	mVertexProgram = ShaderManager::Instance()->GetProgram(mVertex);
	mParamMvp = cgGetNamedParameter(mVertexProgram, "mvp");
	mParamWorldMatrix = cgGetNamedParameter(mVertexProgram, "worldMatrix");
	mOutColor = cgGetNamedParameter(mVertexProgram, "outColor");
	CGparameter mEyePosition = cgGetNamedParameter(mVertexProgram, "eyePosition");
	cgSetParameter3f(mEyePosition, 0, 0, 13);

	mFragment = ShaderManager::Instance()->CreateShader(SID_SAMPLE_OUT_LINE_FRAGMENT);
	ShaderManager::Instance()->LoadShader(mFragment);
	mFragmentProgram = ShaderManager::Instance()->GetProgram(mFragment);

	glMatrixMode(GL_PROJECTION);
	gluPerspective(40, 1, 1, 20);
	glGetFloatv(GL_PROJECTION_MATRIX, mProject);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	gluLookAt(0, 0, 13, 0, 0, 0, 0, 1, 0);
	glGetFloatv(GL_MODELVIEW_MATRIX, mView);

	mRotateAngleY = 0;
}

void OutLineRender::draw()
{
	ShaderManager::Instance()->BindShader(mVertex);
	ShaderManager::Instance()->EnableShaderProfile(mVertex);
	ShaderManager::Instance()->BindShader(mFragment);
	ShaderManager::Instance()->EnableShaderProfile(mFragment);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glTranslatef(0, -1, 2);
	glRotatef(mRotateAngleY, 0, 1, 0);
	glRotatef(-90, 1, 0, 0);
	glGetFloatv(GL_MODELVIEW_MATRIX, mModel);

	glLoadMatrixf(mProject);
	glMultMatrixf(mView);
	glMultMatrixf(mModel);
	glGetFloatv(GL_MODELVIEW_MATRIX, mModelViewProject);

	cgSetMatrixParameterfr(mParamMvp, mModelViewProject);
	cgSetMatrixParameterfr(mParamWorldMatrix, mModel);
	cgSetParameter3f(mOutColor, 0, 1, 0);

	glEnable(GL_CULL_FACE);
	glFrontFace(GL_CCW);
	glCullFace(GL_FRONT);
	glDisable(GL_DEPTH_TEST);
	glutSolidTeapot(1);
	glEnable(GL_DEPTH_TEST);
	glDisable(GL_CULL_FACE);

	ShaderManager::Instance()->UnBindShader(mFragment);
	ShaderManager::Instance()->DisableShaderProfile(mFragment);

	ShaderManager::Instance()->BindShader(mVertexNormal);
	ShaderManager::Instance()->EnableShaderProfile(mVertexNormal);
	cgSetMatrixParameterfr(mParamMvpNormal, mModelViewProject);
	glutSolidTeapot(1);
	ShaderManager::Instance()->UnBindShader(mVertexNormal);
	ShaderManager::Instance()->DisableShaderProfile(mVertexNormal);
	

	ShaderManager::Instance()->UnBindShader(mVertex);
	ShaderManager::Instance()->DisableShaderProfile(mVertex);
}

void OutLineRender::idle()
{
	mRotateAngleY += 1.0f;
	if (mRotateAngleY >= 360.0f)
	{
		mRotateAngleY -= 360.0f;
	}
}